package jp.wug.util;

import java.io.UnsupportedEncodingException;
import java.net.URLEncoder;

public class QueryParameters {
    private final StringBuffer buffer = new StringBuffer();
    private String contextPathPlusServletPath;
    private String pathInfo = "";

    public QueryParameters(String contextPathPlusServletPath) {
        this.contextPathPlusServletPath = contextPathPlusServletPath;
    }

    private String encode(String string) {
        try {
            return URLEncoder.encode(string, "UTF-8");
        } catch (UnsupportedEncodingException e) {
            throw new Error(e);
        }
    }

    public void append(String key, String value) {
        if (buffer.length() > 0) {
            buffer.append("&");
        }
        buffer.append(encode(key));
        buffer.append("=");
        if (value == null) {

        } else {
            buffer.append(encode(value));
        }
    }

    public void setPathInfo(String pathInfo) {
        this.pathInfo = pathInfo;
    }

    public String toPath() {
        if (buffer.length() > 0) {
            return contextPathPlusServletPath + pathInfo + "?" + buffer;
        } else {
            return contextPathPlusServletPath + pathInfo;
        }
    }
}